package cn.fl.warrant.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.service.IArcApplyDetailService;
import cn.fl.warrant.service.IArcApplyMainService;
import cn.fl.warrant.service.IArcBscInfoService;
import cn.fl.warrant.service.IArcMgrMainService;
import cn.fl.warrant.service.IArcPostInfoService;
import cn.fl.warrant.service.IArcReceiptMainService;
import cn.fl.warrant.transform.ArcMgrDetailVOTransform;
import cn.fl.warrant.transform.ArcMgrMainVOTransform;
import cn.fl.warrant.transform.ArcReceiptDetailVOTransform;
import cn.fl.warrant.vo.ArcApplyDetailVO;
import cn.fl.warrant.vo.ArcApplyMainVO;
import cn.fl.warrant.vo.ArcBscInfoVO;
import cn.fl.warrant.vo.ArcMgrDetailVO;
import cn.fl.warrant.vo.ArcMgrMainVO;
import cn.fl.warrant.vo.ArcPostInfoVO;
import cn.fl.warrant.vo.ArcReceiptDetailVO;
import cn.fl.warrant.vo.ArcReceiptMainVO;
import cn.fl.warrant.vo.ArcSysFlowSHVO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.warrant.facade.archive.api.IArcApplyMainApiService;
import fl.warrant.facade.archive.api.IArcMgrDetailApiService;
import fl.warrant.facade.archive.api.IArcMgrMainApiService;
import fl.warrant.facade.archive.condition.ArcApplyDetailQC;
import fl.warrant.facade.archive.condition.ArcApplyMainQC;
import fl.warrant.facade.archive.condition.ArcMgrDetailQC;
import fl.warrant.facade.archive.condition.ArcMgrMainQC;
import fl.warrant.facade.archive.condition.ArcPostInfoQC;
import fl.warrant.facade.archive.condition.ArcReceiptDetailQueryCondition;
import fl.warrant.facade.archive.condition.ArcReceiptMainQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcMgrDetailDTO;
import fl.warrant.facade.archive.dto.ArcMgrMainDTO;
import fl.warrant.facade.archive.dto.ArcReceiptMainDTO;

/**
 * @Description: 档案管理主表(旧表：T_API_DOCUMENT_RENTPLAN) 控制层
 */
@Controller
@RequestMapping("/archive/arcMgrMain")
public class ArcMgrMainController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcMgrMainController.class);
	/**
     * 项目基础服务
     */
    @Autowired
    private IPrjBscInfoService prjBscInfoService;
    
	/**
	 * ArcMgrMain 服务层BEAN
	 */
	@Autowired
	private IArcMgrMainService arcMgrMainService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	@Autowired
	private IArcPostInfoService arcPostInfoService;
	@Autowired
	private IArcReceiptMainService arcReceiptMainService;
	@Autowired
	private IArcBscInfoService arcBscInfoService;
	@Autowired
	private IArcApplyMainApiService arcApplyMainApiService;
	@Autowired
	private IArcApplyMainService arcApplyMainService ;
	@Autowired
	private IArcApplyDetailService arcApplyDetailService; 
	@Autowired
	private ISysUsrApiService sysUsrApiService;
	
	@Autowired
	private IArcMgrMainApiService arcMgrMainApiService;
	@Autowired
	private IArcMgrDetailApiService arcMgrDetailApiService;
	
	private Map getParms(HttpServletRequest request){
		Map map=new HashMap();
		Enumeration enu=request.getParameterNames();  
		StringBuffer sb = new StringBuffer();
		while(enu.hasMoreElements()){  
		String paraName=(String)enu.nextElement();  
			map.put(paraName, request.getParameter(paraName));
		}
		return map;
	}
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public String toListPage(HttpServletRequest request, HttpServletResponse response) {
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		
		
		//获取归档状态
		request.setAttribute("archiveStateList", arcMgrMainService.getStorageStatusList());
		
		//业务类型
		//List<KeyValueVO> bizTypeList = prjBscInfoService.getBizTypeList();
		//request.setAttribute("bizTypeList", bizTypeList);
		
		//支付表状态
		//request.setAttribute("prdStsCdList", this.prjBscInfoService.getPrdStsCdList());
  		//放款状态
		//request.setAttribute("payStsCdList", this.sysDictionaryApiService.getKvList(CapPayInfoConstant.CODE_PAY_STS_CD, sysCd,orgCd));
		//事业部
		List<KeyValueVO> orgList = this.cstBscInfoService.searchBusinessOrgList();
		request.setAttribute("buOrgCdList", orgList);
		//省公司
		request.setAttribute("prList", arcMgrMainService.getPrList());
		
//		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		System.out.println("================"+request.getParameter("tab"));
		if (request.getParameter("tab")!=null&&request.getParameter("tab").equals("b")) {
			return "archive/arcMgr/arcMgrMainList_Lose";
		}else {
			return "archive/arcMgr/arcMgrMainList";
		}
		
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(ArcMgrMainQC qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String searchName = request.getParameter("demo.name");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		if (StringUtils.isNotEmpty(searchName)) {
			//TODO SOMTHING
		}
		//权限添加
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.arcMgrMainService.selectListForListPage(page);
		List<ArcMgrMainVO> list = (List<ArcMgrMainVO>) pager.getResultList();
		ListPageVO<ArcMgrMainVO> listPage = new ListPageVO<ArcMgrMainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("archive/arcMgrMain/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view; 
	}


	/**
	 * 得到一条记录查看详情
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/viewDetail.do", method = { RequestMethod.GET})
	public String viewDetail(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String paySchId = request.getParameter("paySchId");
		String contractNo = request.getParameter("contractNo");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		request.setAttribute("result",result);
		if(StringUtils.isEmpty(contractNo)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "searchBtn", "查找人,主键不存在.[id="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
			return "archive/info";
		}
		ArcMgrMainQC qc=new ArcMgrMainQC();
//		if (StringUtils.isNotBlank(paySchId)) {
//			qc.setPaySchId(Long.parseLong(paySchId));
//		}
		qc.setContractNo(contractNo);
		List<ArcMgrMainVO> mgrList = this.arcMgrMainService.viewDetail(qc);
		request.setAttribute("mgr",mgrList.get(0));		
		request.setAttribute("mgrList", mgrList);

		ArcMgrMainVO cVo= this.arcMgrMainService.selectByContractNo(contractNo);//查询合同权证
		request.setAttribute("cVo",cVo);		

		this.arcMgrMainService.setAttribute(request);//筛选条件查询
		//邮寄信息
		List<ArcPostInfoVO> plist=new ArrayList<ArcPostInfoVO>();
		ArcApplyMainQC aqc=new ArcApplyMainQC();
		aqc.setContractNo(contractNo);
		List<ArcSysFlowSHVO> list=this.arcApplyMainService.searchApplyFlow(aqc);
		if (list!=null) {
			for (int i = 0; i < list.size(); i++) {				
				ArcPostInfoQC condition2=new ArcPostInfoQC();
				condition2.setArcAppId(list.get(i).getDataId());
				List<ArcPostInfoVO> plist2=this.arcPostInfoService.searchList(condition2);
				if (plist2!=null) {
					for (int j = 0; j < plist2.size(); j++) {
						plist2.get(j).setpNo(list.get(i).getpNo());
					}
					plist.addAll(plist2);
				}
				
			}
		}
		request.setAttribute("plist",plist);	
		BaseLogUtils.info(logger, "viewDetail", "跳转到详情页面.[contractNo="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
		
		return "archive/arcMgr/arcMgrDetail";
	}
	/**
	 * 跳转到发起流程页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toFlow.do", method = { RequestMethod.GET, RequestMethod.POST})
	public String toFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//String paySchId = request.getParameter("paySchId");
		String contractNo = request.getParameter("contractNo");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		request.setAttribute("result",result);
		if(StringUtils.isEmpty(contractNo)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "searchBtn", "查找人,主键不存在.[id="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
			return "archive/info";
		}
		
		//初始化赋值
		Map rmap=this.setArcMgr(contractNo, null);
		if (rmap==null) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("没找到交接单!");
			//return "没找到交接单！";
			return "archive/info";
		}
		List<ArcMgrMainVO> mgrList=(List<ArcMgrMainVO>)rmap.get("mgrList");
		ArcMgrMainVO cVo=(ArcMgrMainVO)rmap.get("cVo");
		this.arcMgrMainService.setFilSign(mgrList, cVo);

		request.setAttribute("mgr",mgrList.get(0));
		this.arcMgrMainService.setAttribute(request);//筛选条件查询
		request.setAttribute("cVo",cVo);
		
		request.setAttribute("cjson",JSON.toJSON(cVo));
		request.setAttribute("pjson",JSON.toJSON(mgrList));
		request.setAttribute("mgrList", mgrList);	
		BaseLogUtils.info(logger, "toFlow", "跳转到申请页面.[paySchId="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
		return "archive/arcMgr/arcMgrToFlow";	
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//String name = request.getParameter("name");
		//DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		//ArcMgrMainVO cVo= JSON.parseObject(request.getParameter("cjson"), ArcMgrMainVO.class);
		//List<ArcMgrMainVO> mgrList= JSON.parseArray(request.getParameter("pjson"), ArcMgrMainVO.class);
		Map map=new HashMap();
//		map.put("mgrList", mgrList);
		map.putAll(this.getParms(request));
		System.out.println("----"+map);
		String contractNo = request.getParameter("contractNo");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		request.setAttribute("result",result);
		String aId=request.getParameter("arcReceiptMainId");
		if(StringUtils.isEmpty(contractNo)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "searchBtn", "查找人,主键不存在.[id="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		//判断是否已经流程结束
		ArcApplyMainQC aqc=new ArcApplyMainQC();
		aqc.setContractNo(contractNo);
		List<ArcSysFlowSHVO> alist=this.arcApplyMainService.searchApplyFlow(aqc);
		if (alist!=null) {
			for (ArcSysFlowSHVO arcSysFlowSHVO : alist) {
				if ("1".equals(arcSysFlowSHVO.getAudStsCd())) {
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("流程正在归档中");
					BaseLogUtils.info(logger, "searchBtn", "流程正在归档中.[id="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
					return result;
				}
			}
		}else {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("流程是空");
			BaseLogUtils.info(logger, "searchBtn", "流程是空.[id="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			Long arcReceiptMainId=Long.valueOf(0);
			
			//初始化赋值
			Map rmap=this.setArcMgr(contractNo, arcReceiptMainId);
			if (rmap==null) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("没找到交接单!");
				//return "没找到交接单！";
				return result;
			}
			List<ArcMgrMainVO> mgrList=(List<ArcMgrMainVO>)rmap.get("mgrList");
			ArcMgrMainVO cVo=(ArcMgrMainVO)rmap.get("cVo");
			
			//归档中的不做处理
			//if (!"2".equals(cVo.getStorageStatus())) {
				//初始化数据，合同
				for (int i = 0; i < cVo.getArcMgrDetailList().size(); i++) {
					ArcMgrDetailVO vo=cVo.getArcMgrDetailList().get(i);
					//本次归档分数
					//vo.setDossierCountI_Y(vo.getDossierCountI().longValue());
					if (map.get("thisCount_c_code_"+vo.getArcReceiptDetailId())!=null) {
						if (map.get("thisCount_c_code_"+vo.getArcReceiptDetailId())!=null&&
								!"".equals(map.get("thisCount_c_code_"+vo.getArcReceiptDetailId()))) {
							//判断电子,如果是电子，则放的是电子id
							if (ArchiveConstants.DOSSOER_TEMP_3.equals(vo.getDossierTemp()))  {
								vo.setEleId(Long.parseLong(map.get("thisCount_c_code_"+vo.getArcReceiptDetailId()).toString().replaceAll(" ", "")));
								vo.setDossierCountT(vo.getDossierCount());
							}else {
								vo.setDossierCountI(Long.parseLong(map.get("thisCount_c_code_"+vo.getArcReceiptDetailId()).toString().replaceAll(" ", "")));
							}
						}else if(vo.getDossierCountI()==null){
							vo.setDossierCountI(0L);
						}
					}
					
				}
				
			//}
			//保存支付表档案
			List<ArcMgrMainVO> newMgrList=new ArrayList<ArcMgrMainVO>();
			map.put("mgrList", newMgrList);
			//判断是否有支付表归档
			boolean zflag=false;
			StringBuffer vins=new StringBuffer();
			for (int i = 0; i < mgrList.size(); i++) {
				ArcMgrMainVO entity = mgrList.get(i);
				cVo.setPrOrgCdNm(entity.getPrOrgCdNm());
				cVo.setBuOrgCd(entity.getBuOrgCd());
				cVo.setPrjTypCd(entity.getPrjTypCd());
				cVo.setIsInsBiz(entity.getIsInsBiz());
				cVo.setCstNm(entity.getCstNm());
				cVo.setCstMgrId(entity.getCstMgrId());
				if (StringUtils.isNotBlank(entity.getVin())) {
					vins=vins.append("|").append(entity.getVin());
				}
				//流程中的不用管
				//if (!"2".equals(entity.getStorageStatus())) {
					int n=0;//统计有要归档的条数	
					
					for (int j = 0; j< entity.getArcMgrDetailList().size(); j++) {
						ArcMgrDetailVO vo=entity.getArcMgrDetailList().get(j);
						//本次归档分数
						//vo.setDossierCountI_Y(vo.getDossierCountI().longValue());
						if (map.get("thisCount_p_"+entity.getPaySchId()+"_"+vo.getArcReceiptDetailId())!=null
								&&!"".equals(map.get("thisCount_p_"+entity.getPaySchId()+"_"+vo.getArcReceiptDetailId()))) {
							long dn=Long.parseLong(map.get("thisCount_p_"+entity.getPaySchId()+"_"+vo.getArcReceiptDetailId()).toString().replaceAll(" ", ""));
							
							//判断电子,如果是电子，则放的是电子id
							if (ArchiveConstants.DOSSOER_TEMP_3.equals(vo.getDossierTemp()))  {
								vo.setEleId(dn);
								vo.setDossierCountT(vo.getDossierCount());
							}else {
								vo.setDossierCountI(dn);
								//统计有要归档的条数	
								if (dn>0) {
									n++;
								}
							}
						}else if (vo.getDossierCountI()==null) {
							vo.setDossierCountI(0L);
						}
					}
					//统计有要归档的条数 如果大于0则归档中，否则状态不变
					//if (n>0) {
						zflag=true;
						newMgrList.add(entity);
						entity.setEleStorageStatus("2");
						entity.setStorageStatus("2");
					//}
					
				//}
			}
//			if (!zflag) {
//				result.setSuccess(BaseConstant.IS_YESNO_NO);
//				result.setInfo("请填写一个支付表！");
//				return result;
//			}
			////保存支付表档案
			for (int i = 0; i < mgrList.size(); i++) {
				ArcMgrMainVO entity = mgrList.get(i);
				//TODO ADD PARAM
					if (entity.getId()==null) {
						//重复提交判断
						ArcMgrMainQC qc=new ArcMgrMainQC();
						qc.setPaySchNo(entity.getPaySchNo());
						List<ArcMgrMainVO> list=this.arcMgrMainService.selectList(qc);
						if (list!=null&&list.size()>0) {
							result.setSuccess(BaseConstant.IS_YESNO_NO);
							result.setInfo("重复提交！");
							return result;
						}
						Long id = this.arcMgrMainService.add(entity);
					}else {
						boolean success = this.arcMgrMainService.modify(entity);
					}
					
				//}
			}
			//保存合同档案
			cVo.setEleStorageStatus("2");
			cVo.setStorageStatus("2");
			
			if (cVo.getId()==null) {
				
				Long id = this.arcMgrMainService.add(cVo);
			}else {
				boolean success = this.arcMgrMainService.modify(cVo);
			}
			//保存申请信息
			Long arcAppId=this.arcMgrMainService.addApply(cVo,map);
			//保存邮寄信息
			map.put("arcAppId", arcAppId.toString());
			map.put("arcAppType", "1");
			map.put("arcAppBussType", "0");
			map.put("sendPorsonType", "1");
			
			this.arcPostInfoService.addOrUpdate(map);
			
			//发起流程
			Map flwomap=new HashMap();
			flwomap.put("id", arcAppId.toString());
			flwomap.put("cstNm",cVo.getCstNm());
			flwomap.put("buOrgCd", cVo.getBuOrgCd());
			flwomap.put("prjTypCd", cVo.getPrjTypCd());
			flwomap.put("cstMgrId", cVo.getCstMgrId());
			String zgFlag="0";//1资管0非
			//工行卡贷、第三方资管两个选项是资管
			if (cVo.getPrjTypCd()!=null) {
				if (cVo.getIsInsBiz()==1||
						cVo.getPrjTypCd().equals(PrjBscInfoConstant.PRJ_TYP_CD_GHKD)||
						cVo.getPrjTypCd().equals(PrjBscInfoConstant.PRJ_TYP_CD_DSFZGCP)
						||cVo.getPrjTypCd().equals(PrjBscInfoConstant.PRJ_TYP_CD_DSFZGCT)) {
					zgFlag="1";
				}
			}
			flwomap.put("zgFlag", zgFlag);
			
			String keyword="";
			keyword=keyword+cVo.getContractNo()+"|"; 
			keyword=keyword+(cVo.getPrOrgCdNm()==null?"":cVo.getPrOrgCdNm());
			keyword=keyword+vins;
			flwomap.put("keyword",keyword.toString());
			BaseLogUtils.info(logger, "add","关键字--"+keyword.toString());
			DataResultDTO dataResultDTO=this.arcApplyMainService.addFlowStart(flwomap);
			if (!dataResultDTO.getCode().equals(
					BaseExceptionConstant.BASE_EXCEPTION_CODE_200)) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_OPERATE_FAIL);
			}
			if (null != dataResultDTO && null != dataResultDTO.getData()) {
				FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dataResultDTO
						.getData();
				if (StringUtils
						.isNotBlank(flowStartedDTO.getNextOperUsrNames())) {
					result.setInfo("下一个节点操作人:"
							+ flowStartedDTO.getNextOperUsrNames());
				} else {
					result.setInfo("流程发起成功:"+flowStartedDTO.getProcInstanceNo());
				}
				
			}
			BaseLogUtils.info(logger, "add", "新增数据.[id=] DATA:" + JSONObject.toJSONString(cVo), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(contractNo) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(contractNo) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(ArcMgrMainVO entity,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.arcMgrMainService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 查找人
	 */
	@RequestMapping(value = "/searchBtn.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object searchBtn(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String idCardNM = request.getParameter("idCardNM");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(idCardNM)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "searchBtn", "查找人,主键不存在.[id="+idCardNM+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SysUsrDTO entity = null;
		try {
			SysUsrQueryCondition condition=new SysUsrQueryCondition();
			condition.setUsrNm(idCardNM);
			condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
			condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			List<SysUsrDTO> list=this.sysUsrApiService.searchSysUsrList(condition);
			if (list==null||list.size()<1) {
				condition.setUsrNm(null);
				condition.setRlNm(idCardNM);
				list=this.sysUsrApiService.searchSysUsrList(condition);
			}
			if (list!=null&&list.size()>0)  {

				result.setData(list.get(0));
			
			}else {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("没找到用户！");
			}
			BaseLogUtils.info(logger, "searchBtn", "成功.[id="+idCardNM+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "searchBtn", "查找人失败.[id="+idCardNM+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "searchBtn", "查找人失败.[id="+idCardNM+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.GET })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcMgrMainService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	/**
	 * 导入档案
	 */
	@RequestMapping(value = "/importPay.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO importPay( @RequestParam(value = "upfile") MultipartFile upfile,HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if (null == upfile) { 
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("模板文件为空,请选择文件");
			BaseLogUtils.info(logger, "importPay", SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY, CurrentThreadContext.getCurrentUserName());
			return result; 
     
        }
		try {
			String fileName = upfile.getOriginalFilename();//report.xls 
	        String[] names=fileName.split("\\.");
	        if(!names[names.length-1].toLowerCase().equals("xls") ){
	        	result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("上传文件必须是 xls");
				BaseLogUtils.info(logger, "importPay", SysLogConstant.LOG_CMM_ENABLE_FAIL, CurrentThreadContext.getCurrentUserName());
				return result; 
	        }
	        InputStream fis = upfile.getInputStream();  
	        HSSFWorkbook book = new HSSFWorkbook(fis);  
            HSSFSheet sheet = book.getSheetAt(0);
            int firstRow = 1;
            int lastRow = sheet.getLastRowNum();
            //先控制最多1000
            if(lastRow>1003){
	        	result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据条数最多1000");
				BaseLogUtils.info(logger, "importPay", SysLogConstant.LOG_CMM_ENABLE_FAIL, CurrentThreadContext.getCurrentUserName());
				return result; 
	        }
            int num = 0;
            String jString="旧权证归档交接单-";
            String flagString=sheet.getRow(1).getCell(0).getStringCellValue().replaceAll(" ", "");
            jString=jString+flagString;
            //筛选一个交接单			
			ArcReceiptMainQueryCondition rqc=new ArcReceiptMainQueryCondition();
			rqc.setListName(jString);
			List<ArcReceiptMainDTO> rlist = (List<ArcReceiptMainDTO>) this.arcReceiptMainService.searchList(rqc);
			List<ArcMgrDetailVO> clist=new  ArrayList<ArcMgrDetailVO>();
			List<ArcMgrDetailVO> dlist=new  ArrayList<ArcMgrDetailVO>();
			//交接单初始化一份
			Long arcReceiptMainId;
			String arcReceiptName;
			Long versioni;
			if (rlist!=null&&rlist.size()>0) {
				//交接单明细查询
				ArcReceiptDetailQueryCondition rdqc=new ArcReceiptDetailQueryCondition();
				rdqc.setArcReceiptMainId(rlist.get(0).getId());
				String sysCd=CurrentThreadContext.getCurrentSysCd();
				String orgCd=CurrentThreadContext.getCurrentOrgCd();
				List<ArcReceiptDetailVO> arcReceiptDetailVOList = ArcReceiptDetailVOTransform.toVOList(this.arcReceiptMainService.arcReceiptDetailList(rdqc));
				
				//交接单初始化一份
				 arcReceiptMainId=rlist.get(0).getId();
				 arcReceiptName=rlist.get(0).getListName();
				 versioni=rlist.get(0).getVersion();
				//初始化
				for(ArcReceiptDetailVO arcReceiptDetailVO: arcReceiptDetailVOList) {
					
					ArcBscInfoVO arcBscInfoVO = arcBscInfoService.selectById(arcReceiptDetailVO.getArcBscInfo());
					String fileFlagNm="";
					//去除结清资料
					if (ArchiveConstants.FILE_FLAG_5.equals(arcBscInfoVO.getWarrantType())) {
						continue;
					}
					//交接单初始化一份
					{
						ArcMgrDetailVO dVo=new ArcMgrDetailVO();
						//dVo.setArcApplyMainId(mgrd.getArcApplyMainId());//归档申请主表ID
						dVo.setArcReceiptDetailId(arcReceiptDetailVO.getId());//交接单明细ID
						//dVo.setContractNo(contractNo);//融资租赁合同编号
						//dVo.setPaylistCode(mgrd.getPaylistCode());//支付表号
						dVo.setFileFlag(arcBscInfoVO.getWarrantType());//权证类别(合同、权证资料等)[档案基础信息]
						dVo.setFileName(arcBscInfoVO.getWarrantName());//权证名称[档案基础信息]
						dVo.setArcLevel(arcBscInfoVO.getArcLevel());//归类级别(合同归类、支付表归类)[档案基础信息]
						dVo.setDossierTemp(arcReceiptDetailVO.getType());//1原件/2复印件/3电子[交接单明细] 
						dVo.setIschoice(arcReceiptDetailVO.getIschoice());//是否必选[交接单明细] 0必选 1 非必选
						dVo.setDossierCount(arcReceiptDetailVO.getFenshu());//要求份数[交接单明细]
						dVo.setDossierCountI(0L);//归档中份数
						dVo.setDossierCountT(0L);//已归档份数
						//dVo.setEleId(mgrd.getEleId());//电子合同ID(从项目电子合同记录表查出)
						//dVo.setThisCount(mgrd.getDossierCount());//本次归档份数
						//dVo.setCheckCount(mgrd.getCheckCount());//权证审核份数
						dVo.setIsValid(1);//是否有效（1：是，0：否）（SYS0021）
						dVo.setIsDel(0);//是否删除（1：是，0：否）
						dVo.setFileFlagNm(arcBscInfoVO.getWarrantTypeNm());//权证类别(合同、权证资料等)[档案基础信息]
						dVo.setArcLevelNm(arcBscInfoVO.getArcLevelNm());//归类级别(合同归类、支付表归类)[档案基础信息]
						dVo.setUpUsrCd(arcReceiptDetailVO.getUpUserCd());//操作人
						//dVo.setDossierTempNm(arcReceiptDetailVO.getTypeNm());//1原件/2复印件/3电子[交接单明细] 
						//dVo.setIschoiceNm(arcReceiptDetailVO.getIschoice());//是否必选[交接单明细] 0必选 1 非必选
						dVo.setArcReceiptDetailVO(arcReceiptDetailVO);
						//区分合同，支付表
						if (arcBscInfoVO.getArcLevel().equals(ArchiveConstants.ARCLEVEL_2)) {
							dlist.add(dVo);
						}else {
							clist.add(dVo);
						}
						
					}
				}
				
				
			}else {//没找到交接单
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("没找到交接单!");
				//return "没找到交接单！";
				return result;
			}
            String paySchCd1="系统没有的支付表：";
            String paySchCd2="已归档的支付表：";
            
            HSSFRow row = sheet.getRow(0);
            for(int i = firstRow; i < lastRow + 1; i++) { 
            	//总部档案袋编号
            	String dString=sheet.getRow(i).getCell(4).getStringCellValue().replaceAll(" ", "");
            	HSSFRow row1=sheet.getRow(i);
        		if (row1.getCell(0)==null) {
					break;
				}
        		//支付表号
            	String payCode=sheet.getRow(i).getCell(1).getStringCellValue().replaceAll(" ", "");
            	String contractNo=sheet.getRow(i).getCell(2).getStringCellValue().replaceAll(" ", "");
            	if (payCode.equals("")||contractNo.equals("")) {
					break;
				}
            	//归档数赋值
            	for (int j = 5; j <= row.getLastCellNum(); j++) {
            		if (row.getCell(j)==null) {
						break;
					}
            		String nameString=row.getCell(j).getStringCellValue().replaceAll(" ", "");
            		
            		long numString=(long)sheet.getRow(i).getCell(j).getNumericCellValue(); 
            		
            		for (ArcMgrDetailVO dVo :clist) {
						if (StringUtils.isNotBlank(nameString)&& dVo.getFileName().contains(nameString)) {
							dVo.setDossierCountT(Long.valueOf(numString));
							dVo.setContractNo(contractNo);
							dVo.setPaylistCode(payCode);
							break;
						}
					}
            		for (ArcMgrDetailVO dVo :dlist) {
            			if (StringUtils.isNotBlank(nameString)&& dVo.getFileName().contains(nameString)) {
							dVo.setDossierCountT(Long.valueOf(numString));
							dVo.setContractNo(contractNo);
							dVo.setPaylistCode(payCode);
							break;
						}
					}
				}
            	
            	//根据支付表号查询是否已归档
        		ArcMgrMainQC qc=new ArcMgrMainQC();
        		qc.setContractNo(contractNo);
        		//已经归档的支付表
        		//List<ArcMgrMainVO> mgrList = this.arcMgrMainService.viewDetail(qc);
        		String sysCd=CurrentThreadContext.getCurrentSysCd();
        		String orgCd=CurrentThreadContext.getCurrentOrgCd();
        		Pager pager=new Pager();
        		pager.setCurrentPage(0);
        		pager.setEveryPage(10000);
        		pager.setCondition(qc);
        		List<ArcMgrMainVO> mgrList=(List<ArcMgrMainVO>)this.arcMgrMainService.selectListForListPage(pager).getResultList();
        		if (mgrList!=null) {
        			for (ArcMgrMainVO vo:mgrList) {
        				if (vo.getId()!=null) {
        					ArcMgrDetailQC dQc=new ArcMgrDetailQC();
        					dQc.setArcMgrMainId(vo.getId());
        					List<ArcMgrDetailVO> list=ArcMgrDetailVOTransform.toVOList(arcMgrDetailApiService.searchList(dQc, sysCd,orgCd ));
        					vo.setArcMgrDetailList(list);
        				}
        				
        			}
        		}
        		if (mgrList!=null&&mgrList.size()>0) {
        			//已经归档，重新归一次
					if (mgrList.get(0).getArcReceiptName()!=null&&mgrList.get(0).getArcReceiptName().equals(jString)) {
						//ArcMgrMainVO cVo= this.arcMgrMainService.selectByContractNo(contractNo);//查询合同权证
						ArcMgrMainDTO dto = this.arcMgrMainApiService.selectByContractNo(contractNo);
						ArcMgrMainVO cVo=ArcMgrMainVOTransform.toVO(dto);
						if (cVo!=null&&cVo.getId()!=null) {
							ArcMgrDetailQC dQc=new ArcMgrDetailQC();
							dQc.setArcMgrMainId(cVo.getId());
							List<ArcMgrDetailDTO> list=this.arcMgrDetailApiService.searchList(dQc, sysCd,orgCd );
							cVo.setArcMgrDetailList(ArcMgrDetailVOTransform.toVOList(list));
						}else {
							paySchCd1=paySchCd1+payCode+",";
							continue;
						}
						
						//合同归档数据
						for (ArcMgrDetailVO dVo :cVo.getArcMgrDetailList()) {
							for (ArcMgrDetailVO dVo1 :clist) {
								if (dVo1.getFileName().equals(dVo.getFileName())) {
									dVo.setDossierCountT(dVo1.getDossierCountT());
									break;
								}
							}
							
						}
						cVo.setPortfolioNumber(dString);
						this.arcMgrMainService.modify(cVo);
						//支付表归档数据
						for (ArcMgrMainVO mVo :mgrList) {
							if (payCode.equals(mVo.getPaySchNo())) {
								for (ArcMgrDetailVO dVo :mVo.getArcMgrDetailList()) {
									for (ArcMgrDetailVO dVo1 :dlist) {
										if (dVo1.getFileName().equals(dVo.getFileName())) {
											dVo.setDossierCountT(dVo1.getDossierCountT());
											break;
										}
									}
									
								}
								mVo.setPortfolioNumber(dString);
								this.arcMgrMainService.modify(mVo);
								break;
							}
						}
					//已经归档为其他，不再归档	
					}else if(mgrList.get(0).getArcReceiptName()!=null){
						paySchCd2=paySchCd2+payCode+",";
						continue;
					//没有归档，匹配交接单		
					}else if(mgrList.get(0).getArcReceiptName()==null){						
						//交接单主表赋值	合同	
						ArcMgrMainVO cVo=new ArcMgrMainVO();
						cVo=ArcMgrMainVOTransform.toVO(ArcMgrMainVOTransform.toDTO(mgrList.get(0)));
						cVo.setArcMgrDetailList(clist);
						cVo.setPaySchId(null);
						cVo.setPaySchNo(null);
						cVo.setArcReceiptMainId(arcReceiptMainId);
						cVo.setArcReceiptName(arcReceiptName);
						cVo.setVersioni(versioni);
						cVo.setPortfolioNumber(dString);
						cVo.setStorageStatus("4");
						cVo.setEleStorageStatus("1");
						this.arcMgrMainService.add(cVo);
						for (ArcMgrMainVO dVo :mgrList) {
							List<ArcMgrDetailVO> ddList=ArcMgrDetailVOTransform.toVOList(ArcMgrDetailVOTransform.toDTOList(dlist));
							dVo.setArcMgrDetailList(ddList);
							dVo.setArcReceiptMainId(arcReceiptMainId);
							dVo.setArcReceiptName(arcReceiptName);
							dVo.setVersioni(versioni);
							//匹配支付表,如果不是当前的归档分数为0
							if (!payCode.equals(mgrList.get(0).getPaySchNo())) {
								for (ArcMgrDetailVO ddVo: ddList) {
									ddVo.setDossierCountT(0L);
								}
							}
							dVo.setPortfolioNumber(dString);
							dVo.setStorageStatus("4");
							dVo.setEleStorageStatus("1");
							this.arcMgrMainService.add(dVo);
						}
					}
				}else {
					paySchCd1=paySchCd1+payCode+",";
					continue;
				}
            	
            }
            result.setInfo(paySchCd1+paySchCd2);
			BaseLogUtils.info(logger, "importPay", "导入档案.[id=]", CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "importPay", "导入档案失败"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	/**
	 * 交接单明细初始化
	 * @param list
	 * @param clist
	 * @param dlist
	 * 2018年12月29日 
	 * lxb
	 */
	public Map<String,Object> setArcMgr(String contractNo,Long arcReceiptMainId ){
		List<ArcMgrMainVO> mgrList=null;
		ArcMgrMainVO cVo=null;
		ArcMgrMainQC qc=new ArcMgrMainQC();
//		if (StringUtils.isNotBlank(paySchId)) {
//			qc.setPaySchId(Long.parseLong(paySchId));
//		}
		qc.setContractNo(contractNo);
		String sysCd=CurrentThreadContext.getCurrentSysCd();
		String orgCd=CurrentThreadContext.getCurrentOrgCd();
		Pager pager=new Pager();
		pager.setCurrentPage(0);
		pager.setEveryPage(10000);
		pager.setCondition(qc);
		//已经归档的支付表
		mgrList=(List<ArcMgrMainVO>)this.arcMgrMainService.selectListForListPage(pager).getResultList();
		if (mgrList!=null) {
			for (int i = 0; i < mgrList.size(); i++) {
				ArcMgrMainVO vo=mgrList.get(i);
				if (vo.getId()!=null) {
					
					ArcMgrDetailQC dQc=new ArcMgrDetailQC();
					dQc.setArcMgrMainId(vo.getId());
					List<ArcMgrDetailVO> list=ArcMgrDetailVOTransform.toVOList(arcMgrDetailApiService.searchList(dQc, sysCd,orgCd ));
					vo.setArcMgrDetailList(list);
				}
				
			}
		}
		
		//判断是否已经归档
		String arcReceiptName="";
		Long versioni=null;
		List<ArcMgrDetailVO> clist=new ArrayList<ArcMgrDetailVO>();//合同类权证
		List<ArcMgrDetailVO> dlist=new ArrayList<ArcMgrDetailVO>();//支付表类权证
		ArcMgrMainDTO dto = this.arcMgrMainApiService.selectByContractNo(contractNo);
		 cVo=ArcMgrMainVOTransform.toVO(dto);
		if (cVo!=null&&cVo.getId()!=null) {
			ArcMgrDetailQC dQc=new ArcMgrDetailQC();
			dQc.setArcMgrMainId(cVo.getId());
			sysCd=CurrentThreadContext.getCurrentSysCd();
			orgCd=CurrentThreadContext.getCurrentOrgCd();
			List<ArcMgrDetailDTO> list=this.arcMgrDetailApiService.searchList(dQc, sysCd,orgCd );
			List<ArcMgrDetailVO> list1=ArcMgrDetailVOTransform.toVOList(list);
			cVo.setArcMgrDetailList(list1);
		}
		//交接单主表赋值
		if (cVo!=null) {
		if (mgrList!=null&&mgrList.size()>0) {
			for (int i = 0; i < mgrList.size(); i++) {
				ArcMgrMainVO vo=mgrList.get(i);
				
				if (vo.getArcReceiptMainId()!=null ) {
					//交接单初始化一份
					arcReceiptMainId=vo.getArcReceiptMainId();
					arcReceiptName=vo.getArcReceiptName();
					versioni=vo.getVersioni();
					dlist=vo.getArcMgrDetailList();
					
					break;
				}
			}
		}
		}else{
		//未归档的，如果有归档的则直接用交接单，否则筛选
		
			//筛选一个交接单
			if (arcReceiptMainId==null||arcReceiptMainId==0) {
					
				ArcMgrMainVO mvo=mgrList.get(0);
				ArcReceiptMainQueryCondition rqc=new ArcReceiptMainQueryCondition();
				if (StringUtils.isNotBlank(mvo.getBuOrgCd())) {//事业部SYS0031
					rqc.setBuOrgCd(mvo.getBuOrgCd());
				}
				if (StringUtils.isNotBlank(mvo.getBizTypCd())) {//业务类型（PRJ0006）
					rqc.setPrjBizType(mvo.getBizTypCd());
				}
				if (StringUtils.isNotBlank(mvo.getCstTypCd())) {//客户分类（CST0001）
					rqc.setLesseeType(mvo.getCstTypCd());
				}
				if (StringUtils.isNotBlank(mvo.getCntTypCd())) {//合同签署方式PRJ0047
					rqc.setContractSign(mvo.getCntTypCd());
				}
				if (StringUtils.isNotBlank(mvo.getIsDb())) {//是否有担保人
					rqc.setGuarantee(mvo.getIsDb());
				}
				if (StringUtils.isNotBlank(mvo.getCstTypCd2())) {//多个担保人类型
					rqc.setGuaranteeType(mvo.getCstTypCd2());
				}
				if (StringUtils.isNotBlank(mvo.getCntTypCd2())) {//担保人合同签署方式
					rqc.setGuaranteeSign(mvo.getCntTypCd2());
				}
				if (StringUtils.isNotBlank(mvo.getPrjTypCd())) {//项目类型PRJ0002
					rqc.setProjectType(mvo.getPrjTypCd());
				}
				
				if (StringUtils.isNotEmpty(mvo.getIsInsBiz())) {//是否资管
					rqc.setAssetManage(String.valueOf(mvo.getIsInsBiz()));
					if (mvo.getIsInsBiz()==1&&StringUtils.isNotEmpty(mvo.getFundRasInsId())) {//金融机构
						rqc.setFundCompany(mvo.getFundRasInsId().toString());
					}
				}
				List<ArcReceiptMainVO> list = (List<ArcReceiptMainVO>) this.arcReceiptMainService.selectListForMgr(rqc);
				if (list!=null&&list.size()>0) {
					//交接单初始化一份
					arcReceiptMainId=list.get(0).getId();
					arcReceiptName=list.get(0).getListName();
					versioni=list.get(0).getVersion();
				}else {//没找到交接单
					
					//return "没找到交接单！";
					return null;
				}
			}else {
				ArcReceiptMainVO receiptMainVO=this.arcReceiptMainService.selectById(arcReceiptMainId);
				//交接单初始化一份
				arcReceiptMainId=receiptMainVO.getId();
				arcReceiptName=receiptMainVO.getListName();
				versioni=receiptMainVO.getVersion();
			}
			//交接单初始化一份
			//交接单明细查询
			ArcReceiptDetailQueryCondition rdqc=new ArcReceiptDetailQueryCondition();
			rdqc.setArcReceiptMainId(arcReceiptMainId);
			List<ArcReceiptDetailVO> arcReceiptDetailVOList = ArcReceiptDetailVOTransform.toVOList(this.arcReceiptMainService.arcReceiptDetailList(rdqc));
			List<KeyValueVO> list5= this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC005, sysCd, orgCd);
			List<KeyValueVO> list2= this.sysDictionaryApiService.getKvList(ArchiveConstants.SYS0021, sysCd, orgCd);
			
			//初始化
			for(int i=0;i<arcReceiptDetailVOList.size();i++) {
				ArcReceiptDetailVO arcReceiptDetailVO = arcReceiptDetailVOList.get(i);
				
				ArcBscInfoVO arcBscInfoVO = arcBscInfoService.selectById(arcReceiptDetailVO.getArcBscInfo());
				String fileFlagNm="";
				if(arcBscInfoVO != null) {
					arcReceiptDetailVO.setWarrantName(arcBscInfoVO.getWarrantName());
					SysDictionaryDTO dictionary  = sysDictionaryApiService.getCode(ArchiveConstants.SYS_CODE, ArchiveConstants.ORG_CODE,
							ArchiveConstants.ARC001, arcBscInfoVO.getWarrantType());
					if(dictionary != null){
						fileFlagNm=dictionary.getCodeNm();
					}
					
				}
				//去除结清资料
				if (arcBscInfoVO.getWarrantType()!=null&&ArchiveConstants.FILE_FLAG_5.equals(arcBscInfoVO.getWarrantType())) {
					continue;
				}
				//交接单初始化一份
				{
					ArcMgrDetailVO dVo=new ArcMgrDetailVO();
					//dVo.setArcApplyMainId(mgrd.getArcApplyMainId());//归档申请主表ID
					dVo.setArcReceiptDetailId(arcReceiptDetailVO.getId());//交接单明细ID
					dVo.setContractNo(contractNo);//融资租赁合同编号
					//dVo.setPaylistCode(mgrd.getPaylistCode());//支付表号
					dVo.setFileFlag(arcBscInfoVO.getWarrantType());//权证类别(合同、权证资料等)[档案基础信息]
					dVo.setFileName(arcBscInfoVO.getWarrantName());//权证名称[档案基础信息]
					dVo.setArcLevel(arcBscInfoVO.getArcLevel());//归类级别(合同归类、支付表归类)[档案基础信息]
					dVo.setDossierTemp(arcReceiptDetailVO.getType());//1原件/2复印件/3电子[交接单明细] 
					dVo.setIschoice(arcReceiptDetailVO.getIschoice());//是否必选[交接单明细] 0必选 1 非必选
					dVo.setDossierCount(arcReceiptDetailVO.getFenshu());//要求份数[交接单明细]
					dVo.setDossierCountI(0L);//归档中份数
					dVo.setDossierCountT(0L);//已归档份数
					//dVo.setEleId(mgrd.getEleId());//电子合同ID(从项目电子合同记录表查出)
					//dVo.setThisCount(mgrd.getDossierCount());//本次归档份数
					//dVo.setCheckCount(mgrd.getCheckCount());//权证审核份数
					dVo.setIsValid(1);//是否有效（1：是，0：否）（SYS0021）
					dVo.setIsDel(0);//是否删除（1：是，0：否）
					dVo.setFileFlagNm(arcBscInfoVO.getWarrantTypeNm());//权证类别(合同、权证资料等)[档案基础信息]
					dVo.setArcLevelNm(arcBscInfoVO.getArcLevelNm());//归类级别(合同归类、支付表归类)[档案基础信息]
					dVo.setUpUsrCd(arcReceiptDetailVO.getUpUserCd());//操作人
					//交接单明细
					for (int i2 = 0; i2 < list5.size(); i2++) {
						KeyValueVO kv=list5.get(i2);
						if (kv.getKey().equals(dVo.getDossierTemp())) {
							dVo.setDossierTempNm(kv.getValue());
							break;
						}
					}
					//是否必选
					for (int i2 = 0; i2 < list2.size(); i2++) {
						KeyValueVO kv=list2.get(i2);
						if (kv.getKey().equals(dVo.getIschoice())) {
							dVo.setIschoiceNm(kv.getValue());
							break;
						}
					}
					//dVo.setDossierTempNm(arcReceiptDetailVO.getTypeNm());//1原件/2复印件/3电子[交接单明细] 
					//dVo.setIschoiceNm(arcReceiptDetailVO.getIschoice());//是否必选[交接单明细] 0必选 1 非必选
					dVo.setArcReceiptDetailVO(arcReceiptDetailVO);
					//区分合同，支付表
					if (arcBscInfoVO.getArcLevel().equals(ArchiveConstants.ARCLEVEL_2)) {
						dlist.add(dVo);
					}else {
						clist.add(dVo);
					}
					
				}
			}
			
			//交接单主表赋值		
					cVo=new ArcMgrMainVO();
					cVo=ArcMgrMainVOTransform.toVO(ArcMgrMainVOTransform.toDTO(mgrList.get(0)));
					cVo.setArcMgrDetailList(clist);
					cVo.setPaySchId(null);
					cVo.setPaySchNo(null);
					cVo.setContractNo(contractNo);
					cVo.setArcReceiptMainId(arcReceiptMainId);
					cVo.setArcReceiptName(arcReceiptName);
					cVo.setVersioni(versioni);
					
		}
		
		//获取附件
		this.arcMgrMainService.getFiles(cVo.getArcMgrDetailList());
		//把没有归档的支付表复制一份交接单
		for (int i = 0; i < mgrList.size(); i++) {
			ArcMgrMainVO mVo=mgrList.get(i);
			
			if (mVo.getPaySchId()!=null&&mVo.getArcReceiptMainId()==null) {	
				List<ArcMgrDetailVO> ddList=ArcMgrDetailVOTransform.toVOList(ArcMgrDetailVOTransform.toDTOList(dlist));
				mVo.setArcReceiptMainId(arcReceiptMainId);
				mVo.setArcReceiptName(arcReceiptName);
				mVo.setVersioni(versioni);
				mVo.setArcMgrDetailList(ddList);
				mVo.setPortfolioNumber(cVo.getPortfolioNumber());
				mVo.setPortfolioNumberProvince(cVo.getPortfolioNumberProvince());
				//赋值
				for (int a = 0; a < mVo.getArcMgrDetailList().size();a++) {
					ArcMgrDetailVO dvo=mVo.getArcMgrDetailList().get(a);
					dvo.setId(null);
					dvo.setArcMgrMainId(null);//归档主表ID
					dvo.setContractNo(contractNo);//融资租赁合同编号
					dvo.setPaylistCode(mVo.getPaySchNo());//支付表号
					dvo.setDossierCountI(0L);//归档中份数
					dvo.setDossierCountT(0L);//已归档份数
					dvo.setEleId(null);//电子合同ID(从项目电子合同记录表查出)
					dvo.setFilePath(null);
					//去除结清资料
					if (ArchiveConstants.FILE_FLAG_5.equals(dvo.getFileFlag())) {
						mVo.getArcMgrDetailList().remove(a);
						--a;
						continue;
					}
					
					
				}
				
			}
			//判断是否有两个抵押我司页
			int vflag=0;
			for (int a = 0; a < mVo.getArcMgrDetailList().size();a++) {
				ArcMgrDetailVO dvo=mVo.getArcMgrDetailList().get(a);
				//提前放款流程，处理交接单区别使用 抵押页2 去除抵押页
				if (dvo.getFileName().contains(ArchiveConstants.VE_NAME)
								||dvo.getFileName().contains(ArchiveConstants.VE_NAME2)){
					vflag++;
				}
			}
			if (vflag==2) {				
				//根据放款流程不同，处理交接单区别使用 抵押页2 去除抵押页
				for (int a = 0; a < mVo.getArcMgrDetailList().size();a++) {
						ArcMgrDetailVO dvo=mVo.getArcMgrDetailList().get(a);
						//提前放款流程，处理交接单区别使用 抵押页2 去除抵押页
						if (StringUtils.isNotBlank(mVo.getPrInsNo())
								&&dvo.getFileName()!=null&&
								(dvo.getFileName().contains(ArchiveConstants.VE_NAME_X)
								||dvo.getFileName().contains(ArchiveConstants.VE_NAME))) {
							
								String[] insNo=mVo.getPrInsNo().split("\\.");
								String insNosString=","+insNo[0]+",";
								if (ArchiveConstants.TIQIAN_NO_2.contains(insNosString)) {
									mVo.getArcMgrDetailList().remove(a);
									a--;
									//旧的，删除
	//								if (dvo.getId()!=null) {
	//									this.arcMgrDetailApiService.removeById(dvo.getId());
	//								}
								}
								
							
						}else {
							//其他放款流程，处理交接单区别使用 去除抵押页2
							if (StringUtils.isNotBlank(mVo.getPrInsNo())
									&&dvo.getFileName()!=null&&
									(dvo.getFileName().contains(ArchiveConstants.VE_NAME_X2)
									||dvo.getFileName().contains(ArchiveConstants.VE_NAME2))) {
								
									String[] insNo=mVo.getPrInsNo().split("\\.");
									String insNosString=","+insNo[0]+",";
									if (!ArchiveConstants.TIQIAN_NO_2.contains(insNosString)) {
										mVo.getArcMgrDetailList().remove(a);
										a--;
										//旧的，删除
	//									if (dvo.getId()!=null) {
	//										this.arcMgrDetailApiService.removeById(dvo.getId());
	//									}
									}
								
							}
						}
				}		
				
			}
			//获取附件
			this.arcMgrMainService.getFiles(mVo.getArcMgrDetailList());
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("mgrList", mgrList);
		map.put("arcReceiptMainId", arcReceiptMainId);
		map.put("cVo", cVo);
		return map;	
	}
	/**
	 * 新增
	 */
	@RequestMapping(value = "/addFlow.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		String contractNo=(String)	request.getParameter("contractNo");
		if (StringUtils.isBlank(contractNo)) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键是空");
			BaseLogUtils.info(logger, "addFlow", "新增数据失败.DATA:" + JSONObject.toJSONString(contractNo) + "主键是空", CurrentThreadContext.getCurrentUserName());
		
		}
		try {
			DataResultDTO dataResultDTO=this.arcMgrMainApiService.addFlowStart(contractNo);
			if (dataResultDTO!=null) {
				result.setSuccess(dataResultDTO.getSuccess());
				result.setInfo(dataResultDTO.getInfo());
			}
			
			BaseLogUtils.info(logger, "addFlow", "新增数据.[id=] DATA:" + JSONObject.toJSONString(contractNo), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "addFlow", "新增数据失败.DATA:" + JSONObject.toJSONString(contractNo) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addFlow", "新增数据失败.DATA:" + JSONObject.toJSONString(contractNo) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	/**
	 * 查找人list
	 */
	@RequestMapping(value = "/searchBtnList.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object searchBtnList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String idCardNM = request.getParameter("idCardNM");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(idCardNM)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "searchBtn", "查找人,主键不存在.[id="+idCardNM+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		SysUsrDTO entity = null;
		try {
			SysUsrQueryCondition condition=new SysUsrQueryCondition();
			condition.setUsrNm(idCardNM);
			condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
			condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			List<SysUsrDTO> list=this.sysUsrApiService.searchSysUsrList(condition);
			if (list==null||list.size()<1) {
				condition.setUsrNm(null);
				condition.setRlNm(idCardNM);
				list=this.sysUsrApiService.searchSysUsrList(condition);
			}
			if (list!=null&&list.size()>0)  {
				List<KeyValueVO> dataList=new ArrayList<KeyValueVO>();
				for (SysUsrDTO dto: list) {
					KeyValueVO vo=new KeyValueVO();
					vo.setKey(dto.getUsrNm()+","+dto.getRefRlNm()+","+dto.getMp());
					vo.setValue(dto.getUsrNm()+"|"+dto.getRefRlNm());
					dataList.add(vo);
				}
				result.setData(dataList);
			}else {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("没找到用户！");
			}
			BaseLogUtils.info(logger, "searchBtn", "成功.[id="+idCardNM+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "searchBtn", "查找人失败.[id="+idCardNM+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "searchBtn", "查找人失败.[id="+idCardNM+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 换车流程---【归档信息】
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toMgrInfoView.do", method = { RequestMethod.GET})
	public String toMgrInfoView(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String arcInfoFlag = request.getParameter("arcInfoFlag");
		String contractNo = request.getParameter("contractNo");
		BaseLogUtils.info(logger, "toMgrInfoView", "contractNo"+contractNo+"arcInfoFlag"+arcInfoFlag, CurrentThreadContext.getCurrentUserName());
		
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		request.setAttribute("result",result);
		if(StringUtils.isEmpty(contractNo)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "toMgrInfoView", "查找人,主键不存在.[id="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
			return "archive/info";
		}
		//isFlag=101 标识 没有换车补充协议     isFlag=102标识有换车补充协议
		request.setAttribute("isFlag",101);
		//查询档案管理主表
		ArcMgrMainQC qcc=new ArcMgrMainQC();
		qcc.setContractNo(contractNo);
		List<ArcMgrMainVO> mgrList = this.arcMgrMainService.viewDetail(qcc);
		if(CollectionUtils.isNotEmpty(mgrList)){
			request.setAttribute("mgr",mgrList.get(0));	
		}
		//查询申请主表
		ArcApplyMainQC qc=new ArcApplyMainQC();
		qc.setContractNo(contractNo);
		List<ArcApplyMainVO> applyList = this.arcApplyMainService.selectList(qc);
		BaseLogUtils.newServiceLogger("换车接口调用.归档页签[contractNo="+contractNo+"]"+"mgr=="+JSON.toJSONString(mgrList.get(0))+"==applyList=="+JSON.toJSONString(applyList)).info();
		if(CollectionUtils.isNotEmpty(applyList)) {
			request.setAttribute("apply",applyList.get(0));		
			request.setAttribute("applyList", applyList);
			//申请单明细
			ArcApplyDetailQC dQc=new ArcApplyDetailQC();
			dQc.setArcApplyMainId(Long.valueOf(applyList.get(0).getId()));
			List<ArcApplyDetailVO> aList=this.arcApplyDetailService.searchList(dQc);
			
			List<ArcApplyDetailVO> cList=new ArrayList<ArcApplyDetailVO>();//合同明细
			for (int i = 0; i < aList.size(); i++) {
				ArcApplyDetailVO vo=aList.get(i);
				if (vo.getContractNo()!=null&&vo.getPaylistCode()==null) {
					cList.add(vo);
				}
			}
			
			if(CollectionUtils.isEmpty(cList)){
			}else {
				for(ArcApplyDetailVO detailVO :cList) {
					if("换车补充协议".equals(detailVO.getFileName())){
						request.setAttribute("isFlag",102);
					}
				}
			}//
			request.setAttribute("cList",cList);
			this.arcMgrMainService.setAttribute(request);//筛选条件查询
			
		}
		request.setAttribute("arcInfoFlag",arcInfoFlag);
		request.setAttribute("contractNo", contractNo);
		BaseLogUtils.info(logger, "toMgrInfoView", "跳转到详情页面.[contractNo="+contractNo+"]", CurrentThreadContext.getCurrentUserName());
		
		return "archive/arcMgr/arcMgrInfoView";
	}
	@RequestMapping(value = "/autoAddFlow.do", method = { RequestMethod.GET})
	public String autoAddFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		this.arcMgrMainApiService.autoAddFlow();
		return "1";
	}
}

